package io.renren.modules.merchant.task;

import com.alibaba.fastjson.JSONObject;
import io.renren.modules.merchant.dao.MerchantDao;
import io.renren.modules.merchant.dao.MerchantStatisticsDao;
import io.renren.modules.merchant.service.MerchantService;
import io.renren.modules.order.dao.MerchantOrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("updateSalesTask")
public class updateSalesTask implements ITask {

    @Autowired
    private MerchantDao merchantDao;

    @Autowired
    private MerchantOrderDao merchantOrderDao;

    @Autowired
    private MerchantStatisticsDao merchantStatisticsDao;



    /**
     * 每日23：59:59分执行统计今日销量，覆盖
     *
     * @param params 参数，多参数使用JSON数据
     */
    @Override
    public void run(String params) {
        Map map = new HashMap();
        List<String> merchantIDs = merchantDao.getAllMerchantID();
        LocalDate localDate = LocalDate.now().plusDays(-1);
        //更新每个店铺的销量
        merchantIDs.forEach(merchantID -> {
            map.put("merchantID", merchantID);
            map.put("localDate", localDate);
            map.put("status", 3);
            int turnover = 0;
            int ordersNumber = 0;


            List<Integer> sales = merchantOrderDao.getTurnoverByStatusAndDate(map);
            if (sales != null && sales.size() > 0) {
                ordersNumber = sales.size();
                turnover = sales.stream().reduce(0, Integer::sum);
            }

            map.put("turnover", turnover);
            map.put("orderNumber",ordersNumber);
            //获取日期的号
            map.put("day", localDate.getDayOfMonth());

            merchantStatisticsDao.updateTurnover(map);
        });


    }
}
